<?php

namespace app\admin\controller;

use app\common\enums\StatusEnum;
use think\facade\Request;
use app\admin\model\Role AS RoleModel;
use app\admin\validate\Role AS RoleValidate;
use app\admin\model\Permission;

class Role extends Base
{
    /**
     * 列表
     * @return \think\response\View
     */
    public function index()
    {
        $search = input('');
        $search = [
            'name' => isset($search['name']) ? $search['name'] : '',
            'status' => isset($search['status']) ? $search['status'] : -1,
        ];

        $where = [];
        if ($search['name']) {
            $where[] = ['name', 'like', '%' . $search['name'] . '%'];
        }

        if ($search['status'] != null && $search['status'] != -1) {
            $where['status'] = $search['status'];
        }

        $model = RoleModel::getList($where);
        return view('index', [
            'model' => $model['model'],
            'count' => $model['count'],
            'status' => StatusEnum::$listExplain,
            'where' => $search
        ]);
    }

    /**
     * 添加角色
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function form()
    {
        if (Request::instance()->isPost()) {
            $data = input('post.');

            // 检测变量
            $validate = new RoleValidate();
            if (!$validate->check($data)) {
                return json(self::sendResult(102, [], $validate->getError()));
            }

            $idsStr = implode(',', $data['permission_id']);
            $res = RoleModel::saveOne($data, $idsStr);
            return json(self::sendResult($res['code'], [
                'url' => url('index'),
            ], $res['msg']));

        } else {
            $id = input('id') > 0 ? input('id') : 0;
            $model = [];
            $title = '添加角色';
            if ($id > 0) {
                $model = RoleModel::get($id);
                $title = '编辑角色';
            }

            $permission = Permission::getPermissions($id);
            return view('form', [
                'status' => StatusEnum::$listExplain,
                'model' => $model,
                'permission' => $permission,
                'title' => $title
            ]);
        }
    }

    public function delete($id)
    {
        RoleModel::deleteData($id);
        return self::sendResult(self::$okCode, [
            'url' => url('index'),
        ]);
    }

    public function deletes()
    {
        $ids = input('ids');
        RoleModel::deleteData($ids);

        return self::sendResult(self::$okCode, [
            'url' => url('index'),
        ]);
    }
}